/**
 * Copyright (c) 2010 icer He <icerhe@gmail.com>
 */

package com.icerhe.trigger;

import java.util.Calendar;
import java.util.List;

import com.icerhe.trigger.task.CronTask;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;


public class CronTaskService extends Service {
	
	// Client绑定到此对象,并通过此对象调用Service
	private final IBinder serviceBinder = new TaskServiceBinder();
	
	@Override
	public void onCreate() {
		super.onCreate();
		Log.d(Consts.TAG, "CronTaskService created");
	}


	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		Log.d(Consts.TAG, "CronTaskService start");	
		
		//获取所有当前时间应当触发的任务
		Calendar currentTime = Calendar.getInstance();
		List<CronTask> tasks = TaskHelper.getCronTaskByTime(this, currentTime);
		
		for(CronTask task : tasks) {
			task.runTask(this);
		}
 		
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.d(Consts.TAG, "CronTaskService destory");
	}
	
	public class TaskServiceBinder extends Binder {
		public CronTaskService getService() {
            return CronTaskService.this;
        }
    }

	@Override
	public IBinder onBind(Intent intent) {
		Log.d(Consts.TAG, "CronTaskService onBind");
		return serviceBinder;
	}
	
	@Override
	public void onRebind(Intent intent) {
		super.onRebind(intent);
		Log.d(Consts.TAG, "CronTaskService rebind");
	}

	@Override
	public boolean onUnbind(Intent intent) {
		Log.d(Consts.TAG, "CronTaskService unbind");
		return super.onUnbind(intent);
	}

}
